package com.screen.screendisplay.service.impl.coal;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.screen.screendisplay.entity.coal.CoalProdoperStock;
import com.screen.screendisplay.mapper.coal.CoalProdoperStockMapper;
import com.screen.screendisplay.service.coal.CoalProdoperStockService;
import com.screen.screendisplay.vo.coal.CoalInventoryTrendVO;
import com.screen.screendisplay.vo.coal.CoalInventoryUnitsVO;
import com.screen.screendisplay.vo.wholeproduct.AnnualStockVO;
import com.screen.screendisplay.vo.wholeproduct.CoalStockDetailVO;
import com.screen.screendisplay.vo.wholeproduct.CoalStockYoyVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 生产经营煤炭库存表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class CoalProdoperStockServiceImpl extends ServiceImpl<CoalProdoperStockMapper, CoalProdoperStock> implements CoalProdoperStockService {

    @Override
    public List<CoalInventoryTrendVO> getInventoryTrend(Integer year) {
        // 查询最近6个月的库存数据（unit_code='TOTAL'）
        List<CoalInventoryTrendVO> resultList = new ArrayList<>();
        BigDecimal divisor = new BigDecimal("10000");  // 将吨转换为万吨
        
        for (int i = 0; i < 6; i++) {
            LocalDate monthDate = LocalDate.now().minusMonths(i);
            int queryYear = monthDate.getYear();
            int queryMonth = monthDate.getMonthValue();
            
            CoalInventoryTrendVO vo = new CoalInventoryTrendVO();
            vo.setYear(queryYear);
            vo.setMonth(queryMonth);
            
            // 查询当前年月的库存数据
            LambdaQueryWrapper<CoalProdoperStock> currentQuery = new LambdaQueryWrapper<>();
            currentQuery.eq(CoalProdoperStock::getYear, queryYear)
                       .eq(CoalProdoperStock::getMonth, queryMonth)
                       .eq(CoalProdoperStock::getUnitCode, "TOTAL");
            CoalProdoperStock currentData = this.getOne(currentQuery);
            
            if (currentData != null && currentData.getCurrentStock() != null) {
                vo.setCurrentStock(currentData.getCurrentStock().divide(divisor, 2, RoundingMode.HALF_UP));
            }
            
            // 查询去年同期的库存数据
            int lastYear = queryYear - 1;
            LambdaQueryWrapper<CoalProdoperStock> lastYearQuery = new LambdaQueryWrapper<>();
            lastYearQuery.eq(CoalProdoperStock::getYear, lastYear)
                        .eq(CoalProdoperStock::getMonth, queryMonth)
                        .eq(CoalProdoperStock::getUnitCode, "TOTAL");
            CoalProdoperStock lastYearData = this.getOne(lastYearQuery);
            
            if (lastYearData != null && lastYearData.getCurrentStock() != null) {
                vo.setLastYearStock(lastYearData.getCurrentStock().divide(divisor, 2, RoundingMode.HALF_UP));
            }
            
            resultList.add(vo);
        }
        
        return resultList;
    }

    @Override
    public List<CoalInventoryUnitsVO> getInventoryByUnits(Integer year) {
        // 如果year为null，使用当前年份
        int currentYear = year != null ? year : LocalDate.now().getYear();
        int currentMonth = LocalDate.now().getMonthValue();
        
        // 查询各单位当前月份的库存数据（unit_code != 'TOTAL'）
        LambdaQueryWrapper<CoalProdoperStock> query = new LambdaQueryWrapper<>();
        query.eq(CoalProdoperStock::getYear, currentYear)
             .eq(CoalProdoperStock::getMonth, currentMonth)
             .ne(CoalProdoperStock::getUnitCode, "TOTAL")
             .orderByAsc(CoalProdoperStock::getUnitCode);
        
        List<CoalProdoperStock> dataList = this.list(query);
        
        // 转换为VO列表
        List<CoalInventoryUnitsVO> resultList = new ArrayList<>();
        BigDecimal divisor = new BigDecimal("10000");  // 将吨转换为万吨
        
        for (CoalProdoperStock data : dataList) {
            CoalInventoryUnitsVO vo = new CoalInventoryUnitsVO();
            vo.setUnitName(data.getUnitName());
            vo.setUnitCode(data.getUnitCode());
            
            if (data.getCurrentStock() != null) {
                vo.setCurrentStock(data.getCurrentStock().divide(divisor, 2, RoundingMode.HALF_UP));
            }
            
            resultList.add(vo);
        }
        
        return resultList;
    }

    @Override
    public List<AnnualStockVO> getAnnualStock(Integer year) {
        List<AnnualStockVO> resultList = new ArrayList<>();
        BigDecimal divisor = new BigDecimal("10000");  // 将吨转换为万吨
        
        // 获取当前年份和月份
        int currentYear = LocalDate.now().getYear();
        int currentMonth = LocalDate.now().getMonthValue();
        
        // 查询最近5年的数据
        for (int i = 4; i >= 0; i--) {
            int targetYear = currentYear - i;
            
            // 先尝试查询目标年份当前月份的数据
            LambdaQueryWrapper<CoalProdoperStock> query = new LambdaQueryWrapper<>();
            query.eq(CoalProdoperStock::getYear, targetYear)
                 .eq(CoalProdoperStock::getMonth, currentMonth)
                 .eq(CoalProdoperStock::getUnitCode, "TOTAL");
            
            CoalProdoperStock data = this.getOne(query);
            
            // 如果当前月份没有数据，查询该年最新月份的数据
            if (data == null) {
                LambdaQueryWrapper<CoalProdoperStock> latestQuery = new LambdaQueryWrapper<>();
                latestQuery.eq(CoalProdoperStock::getYear, targetYear)
                          .eq(CoalProdoperStock::getUnitCode, "TOTAL")
                          .orderByDesc(CoalProdoperStock::getMonth)
                          .last("LIMIT 1");
                
                data = this.getOne(latestQuery);
            }
            
            // 如果该年有数据，添加到结果列表
            if (data != null && data.getCurrentStock() != null) {
                AnnualStockVO vo = new AnnualStockVO();
                vo.setYear(targetYear);
                vo.setCurrentStock(data.getCurrentStock().divide(divisor, 2, RoundingMode.HALF_UP));
                resultList.add(vo);
            }
        }
        
        return resultList;
    }

    @Override
    public CoalStockDetailVO getCoalStockDetail(Integer year) {
        CoalStockDetailVO vo = new CoalStockDetailVO();
        BigDecimal divisor = new BigDecimal("10000");  // 将吨转换为万吨
        
        // 获取当前年份和月份
        int currentYear = year != null ? year : LocalDate.now().getYear();
        int currentMonth = LocalDate.now().getMonthValue();
        
        // 查询本月库存数据
        LambdaQueryWrapper<CoalProdoperStock> currentQuery = new LambdaQueryWrapper<>();
        currentQuery.eq(CoalProdoperStock::getYear, currentYear)
                   .eq(CoalProdoperStock::getMonth, currentMonth)
                   .eq(CoalProdoperStock::getUnitCode, "TOTAL");
        CoalProdoperStock currentData = this.getOne(currentQuery);
        
        // 查询上月库存数据
        int lastMonth = currentMonth - 1;
        int lastMonthYear = currentYear;
        if (lastMonth == 0) {
            lastMonth = 12;
            lastMonthYear = currentYear - 1;
        }
        
        LambdaQueryWrapper<CoalProdoperStock> lastMonthQuery = new LambdaQueryWrapper<>();
        lastMonthQuery.eq(CoalProdoperStock::getYear, lastMonthYear)
                     .eq(CoalProdoperStock::getMonth, lastMonth)
                     .eq(CoalProdoperStock::getUnitCode, "TOTAL");
        CoalProdoperStock lastMonthData = this.getOne(lastMonthQuery);
        
        // 设置本月库存量
        if (currentData != null && currentData.getCurrentStock() != null) {
            vo.setCurrentMonthStock(currentData.getCurrentStock().divide(divisor, 2, RoundingMode.HALF_UP));
        }
        
        // 设置上月库存量
        if (lastMonthData != null && lastMonthData.getCurrentStock() != null) {
            vo.setLastMonthStock(lastMonthData.getCurrentStock().divide(divisor, 2, RoundingMode.HALF_UP));
        }
        
        // 计算库存量环比(%) = (本月库存 - 上月库存) / 上月库存 * 100
        if (vo.getCurrentMonthStock() != null && vo.getLastMonthStock() != null 
            && vo.getLastMonthStock().compareTo(BigDecimal.ZERO) != 0) {
            BigDecimal stockMomRate = vo.getCurrentMonthStock().subtract(vo.getLastMonthStock())
                    .divide(vo.getLastMonthStock(), 4, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal("100"))
                    .setScale(2, RoundingMode.HALF_UP);
            vo.setStockMomRate(stockMomRate);
        }
        
        // 设置热量占比（暂时使用固定值，实际应从配置或其他表获取）
        vo.setNormalHeatRatio(new BigDecimal("35.50"));
        vo.setMediumHeatRatio(new BigDecimal("42.30"));
        vo.setHighHeatRatio(new BigDecimal("22.20"));
        
        return vo;
    }

    @Override
    public CoalStockYoyVO getCoalStockYoy(Integer year) {
        CoalStockYoyVO vo = new CoalStockYoyVO();
        BigDecimal divisor = new BigDecimal("10000");  // 将吨转换为万吨
        
        // 获取当前年份和月份
        int currentYear = year != null ? year : LocalDate.now().getYear();
        int currentMonth = LocalDate.now().getMonthValue();
        
        // 查询本月库存数据（当前年、当前月）
        LambdaQueryWrapper<CoalProdoperStock> currentQuery = new LambdaQueryWrapper<>();
        currentQuery.eq(CoalProdoperStock::getYear, currentYear)
                   .eq(CoalProdoperStock::getMonth, currentMonth)
                   .eq(CoalProdoperStock::getUnitCode, "TOTAL");
        CoalProdoperStock currentData = this.getOne(currentQuery);
        
        // 查询去年同期库存数据（去年、当前月）
        int lastYear = currentYear - 1;
        LambdaQueryWrapper<CoalProdoperStock> lastYearQuery = new LambdaQueryWrapper<>();
        lastYearQuery.eq(CoalProdoperStock::getYear, lastYear)
                    .eq(CoalProdoperStock::getMonth, currentMonth)
                    .eq(CoalProdoperStock::getUnitCode, "TOTAL");
        CoalProdoperStock lastYearData = this.getOne(lastYearQuery);
        
        // 设置本月库存量
        if (currentData != null && currentData.getCurrentStock() != null) {
            vo.setCurrentMonthStock(currentData.getCurrentStock().divide(divisor, 2, RoundingMode.HALF_UP));
        }
        
        // 设置去年同期库存量
        if (lastYearData != null && lastYearData.getCurrentStock() != null) {
            vo.setLastYearSamePeriodStock(lastYearData.getCurrentStock().divide(divisor, 2, RoundingMode.HALF_UP));
        }
        
        // 计算库存量同比(%) = (本月库存 - 去年同期库存) / 去年同期库存 * 100
        if (vo.getCurrentMonthStock() != null && vo.getLastYearSamePeriodStock() != null 
            && vo.getLastYearSamePeriodStock().compareTo(BigDecimal.ZERO) != 0) {
            BigDecimal stockYoyRate = vo.getCurrentMonthStock().subtract(vo.getLastYearSamePeriodStock())
                    .divide(vo.getLastYearSamePeriodStock(), 4, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal("100"))
                    .setScale(2, RoundingMode.HALF_UP);
            vo.setStockYoyRate(stockYoyRate);
        }
        
        // 设置热量占比（暂时使用固定值，实际应从配置或其他表获取）
        vo.setNormalHeatRatio(new BigDecimal("35.50"));
        vo.setMediumHeatRatio(new BigDecimal("42.30"));
        vo.setHighHeatRatio(new BigDecimal("22.20"));
        
        return vo;
    }

}
